using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using Serilog;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using WinApp.Models;
using WinApp.Services;

namespace WinApp.Pages
{
    public partial class PageImageMatchActions : UIPage
    {
        #region 属性
        private WebView2 _webView2;
        private Avatar _selectedAvatar = null;
        private ActionOcr _selectedActionOcr = null;
        private ActionImageMatch _selectedAction = null;
        #endregion

        /// <summary>
        /// 刷新页面数据
        /// </summary>
        public void Refresh()
        {
            LoadData();
        }

        public PageImageMatchActions(WebView2 webView2 = null)
        {
            _webView2 = webView2;
            InitializeComponent();
            dgvActions.AutoGenerateColumns = false;
        }

        private async void PageImageMatchActions_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void LoadData()
        {
            try
            {
                // 绑定区域列表
                var regions = DataHelper.GetActionOcrRegions();
                cmbActionOcrs.DataSource = regions;
                cmbActionOcrs.DisplayMember = "Name";
                cmbActionOcrs.ValueMember = "Id";

                // 绑定头像列表
                var avatars = DataHelper.GetAvatars();
                cmbAvatars.DataSource = avatars;
                cmbAvatars.DisplayMember = "Name";
                cmbAvatars.ValueMember = "Id";

                cmbActionOcrs.SelectedIndex = -1;
                cmbAvatars.SelectedIndex = -1;

                // 绑定图像匹配操作列表
                var actions = DataHelper.GetActionImageMatches();
                dgvActions.DataSource = actions;
                dgvActions.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "加载图像匹配页面失败");
                this.ShowErrorTip("加载页面失败：" + ex.Message);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtName.Text))
                {
                    this.ShowWarningTip("请输入动作名称");
                    return;
                }

                if (_selectedActionOcr == null)
                {
                    this.ShowWarningTip("请选择区域");
                    return;
                }

                if (_selectedAvatar == null)
                {
                    this.ShowWarningTip("请选择头像");
                    return;
                }

                var action = new ActionImageMatch
                {
                    ActionOcrId = _selectedActionOcr.Id,
                    AvatarId = _selectedAvatar.Id,
                    Threshold = Convert.ToDouble(txtThreshold.Text)
                };

                bool success = false, existed = false;
                List<ActionImageMatch> actions = dgvActions.DataSource as List<ActionImageMatch>;
                foreach(ActionImageMatch ac in actions)
                {
                    if(ac.ActionOcrId == _selectedActionOcr.Id && ac.AvatarId == _selectedAvatar.Id)
                    {
                        action.Id = ac.Id;
                        success = DataHelper.UpdateActionImageMatch(action);
                        existed = true;
                        break;
                    }
                }
                if (!existed)                
                {
                    success = DataHelper.InsertActionImageMatch(action);
                }

                if (success)
                {
                    this.ShowSuccessTip("保存成功");
                    LoadData();
                }
                else
                {
                    this.ShowErrorTip("保存失败");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "保存图像匹配操作失败");
                this.ShowErrorTip("保存失败：" + ex.Message);
            }
        }

        private async void btnTest_Click(object sender, EventArgs e)
        {            
            try
            {
                if (_webView2 == null || _webView2.CoreWebView2 == null)
                {
                    this.ShowWarningTip("WebView2尚未初始化完成，请等待页面加载");
                    return;
                }

                if (_selectedActionOcr == null)
                {
                    this.ShowWarningTip("请先选择一个区域");
                    return;
                }

                if (_selectedAvatar == null)
                {
                    this.ShowWarningTip("请先选择一个头像");
                    return;
                }
                if(!double.TryParse(txtThreshold.Text, out double threshold))
                {
                    this.ShowWarningTip("请输入一个正确的阈值");
                    return;
                }
                ActionImageMatch action = _selectedAction;
                if (_selectedAction == null)
                {
                    action = new ActionImageMatch
                    {
                        ActionOcr = _selectedActionOcr,
                        Avatar = _selectedAvatar,
                        Threshold = threshold
                    };
                }
                // 获取区域截图
                action.WebView = _webView2;
                action.Completed += (s, e) =>
                {
                    Point pos = Cursor.Position;
                    Point p = _webView2.PointToScreen(Point.Empty);
                    Point np = new Point(p.X + action.ActionOcr.X + e.MatchRect.X, p.Y + action.ActionOcr.Y + e.MatchRect.Y);
                    Cursor.Position = np;
                    this.ShowSuccessTip(e.Descprition);
                    Cursor.Position = pos;
                    // 将结果写入文本框
                    txtResult.Text = $"是否匹配: {((bool)e.IsMatched ? "是" : "否")}\r\n" +
                                   $"匹配度: {e.MatchScore:F4}\r\n" +
                                   $"匹配矩形: X={e.MatchRect.X}, Y={e.MatchRect.Y}, W={e.MatchRect.Width}, H={e.MatchRect.Height}";

                };
                ActionResult rst = await action.ExecuteAsync();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "图像匹配测试失败");
                this.ShowErrorTip($"测试失败：{ex.Message}");
            }
        }

        private void Action_Completed(object? sender, ActionResult e)
        {
            throw new NotImplementedException();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (_selectedAction == null)
                {
                    this.ShowWarningTip("请选择要删除的记录");
                    return;
                }

                if (this.ShowAskDialog("确认删除", "确定要删除选中的记录吗？", UIStyle.Red))
                {
                    if (DataHelper.DeleteActionImageMatch(_selectedAction.Id))
                    {
                        this.ShowSuccessTip("删除成功");
                        LoadData();
                    }
                    else
                    {
                        this.ShowErrorTip("删除失败");
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "删除图像匹配操作失败");
                this.ShowErrorTip("删除失败：" + ex.Message);
            }
        }

        private void cmbActionOcrs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbActionOcrs.SelectedIndex == -1)
            {
                _selectedActionOcr = null;
                txtName.Text = string.Empty;
                return;
            }

            _selectedActionOcr = cmbActionOcrs.SelectedItem as ActionOcr;
            if (_selectedActionOcr != null && _selectedAvatar != null)
            {
                txtName.Text = $"{_selectedActionOcr.Name}识别{_selectedAvatar.Name}";
            }
        }

        private void cmbAvatars_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbAvatars.SelectedIndex == -1)
            {
                pbAvatar.Image?.Dispose();
                pbAvatar.Image = null;
                _selectedAvatar = null;
                txtName.Text = string.Empty;
                return;
            }

            _selectedAvatar = cmbAvatars.SelectedItem as Avatar;
            if (_selectedAvatar != null)
            {
                byte[] imgbs = Convert.FromBase64String(_selectedAvatar.Image);
                using (var ms = new System.IO.MemoryStream(imgbs))
                {
                    pbAvatar.Image?.Dispose();
                    pbAvatar.Image = Image.FromStream(ms);
                }

                if (_selectedActionOcr != null)
                    txtName.Text = $"{_selectedActionOcr.Name}识别{_selectedAvatar.Name}";
            }
        }

        private void dgvActions_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgvActions.SelectedRows.Count == 0 || dgvActions.SelectedIndex == -1)
                {
                    _selectedAction = null;
                    return;
                }

                _selectedAction = dgvActions.SelectedRows[0].DataBoundItem as ActionImageMatch;
                if (_selectedAction != null)
                {
                    txtName.Text = _selectedAction.Name;
                    txtThreshold.Text = _selectedAction.Threshold.ToString();

                    // 设置选中的区域
                    var actionOcr = DataHelper.GetActionOcrById(_selectedAction.ActionOcrId);
                    if (actionOcr != null)
                    {
                        cmbActionOcrs.SelectedValue = actionOcr.Id;
                    }

                    // 设置选中的头像
                    var avatar = DataHelper.GetAvatarById(_selectedAction.AvatarId);
                    if (avatar != null)
                    {
                        cmbAvatars.SelectedValue = avatar.Id;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "选择图像匹配操作失败");
                this.ShowErrorTip("选择失败：" + ex.Message);
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            dgvActions.SelectedIndex = -1;
            cmbAvatars.SelectedIndex = -1;
            cmbActionOcrs.SelectedIndex = -1;
            txtThreshold.DoubleValue = 0.8;
            LoadData();
        }
    }
}
